<template>
  <div class="collection-page">
    <div class="search-container">
      <el-input
        style="width: 400px; margin-right: 10px"
        size="medium"
        v-model="data.name"
        :placeholder="$t('search.inputPlaceholder')"
        prefix-icon="Search"
        clearable
      >
        <template #prepend>
          <!-- 分类选择框 -->
          <el-select
            v-model="data.select"
            :placeholder="$t('search.categoryPlaceholder')"
            style="width: 100px"
            size="large"
            @change="load"
          >
            <!-- 避免空数组调用filter，确保categories有数据再渲染 -->
            <el-option-group
              v-for="category in (data.categories || []).filter(
                (c) => c.parentId === null
              )"
              :key="category.id"
              :label="category.name"
            >
              <!-- 二级分类选项，过滤出该一级分类的子分类 -->
              <el-option
                v-for="subCategory in (data.categories || []).filter(
                  (c) => c.parentId === category.id
                )"
                :key="subCategory.id"
                :label="subCategory.name"
                :value="subCategory.id"
              />
            </el-option-group>
          </el-select>
        </template>
      </el-input>
      <el-button type="primary" @click="load">{{
        $t("search.buttonText")
      }}</el-button>
    </div>

    <section>
      <div class="select-all-container">
        <el-checkbox v-model="checkAll" @change="handleCheckAllChange">{{
          $t("selectAll.checkAllBoxText")
        }}</el-checkbox>
        <el-button
          type="danger"
          @click="batchDelete"
          :disabled="selectedIds.length === 0"
          style="margin-left: 10px"
          >{{ $t("selectAll.batchDeleteButtonText") }}</el-button
        >
      </div>
      <el-row :gutter="20">
        <el-col
          v-for="product in collection.products"
          :key="product.id"
          :span="6"
        >
          <el-card
            class="collect-product-card"
            :body-style="{ padding: '5px' }"
          >
            <el-checkbox
              v-model="product.checked"
              @change="handleCheckChange(product.id)"
            ></el-checkbox>
            <div class="image-container">
              <img
                :src="getProductImage(product)"
                alt="Product Image"
                class="product-image"
              />
            </div>
            <h2
              class="product-name"
              :title="product.name"
              @click="goToDetails(product.id)"
            >
              {{ product.name }}
            </h2>
            <div class="product-info">
              <div class="price">
                <strong style="color: red; font-size: 18px"
                  >￥{{ product.price }}</strong
                >
              </div>
              <div class="stock">
                {{ $t("products.stock") }}：{{ product.stock }}
              </div>
            </div>
            <el-button type="danger" @click="deleteCollect(product.id)">{{
              $t("selectAll.deleteButtonText")
            }}</el-button>
          </el-card>
        </el-col>
      </el-row>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
        />
      </div>
    </section>
  </div>
</template>

<script setup>
import "../../assets/css/Collection.css";
import { onMounted, reactive, ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import router from "@/router/index.js";

// 获取当前用户信息
const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerId = userInfo.id;
console.log("用户ID为：", buyerId);
console.log("用户id类型为：", typeof buyerId);

const data = reactive({
  name: null,
  pageNum: 1,
  pageSize: 10,
  total: 13,
  productList: [],
  checkAll: false,
  select: null,
  categories: [], // 分类数据
});

// 获取分类数据
const loadCategories = () => {
  request
    .get("/Category/selectAll")
    .then((res) => {
      if (res.msg === "成功") {
        data.categories = res.data; // 设置分类数据
      } else {
        ElMessage({
          message: $t("shoppingcart.getCategoriesErrorMessage"),
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("获取分类数据失败", err);
      ElMessage({
        message: $t("shoppingcart.getCategoriesRetryMessage"),
        type: "error",
      });
    });
};

// 获取商品的第一张图片
const getProductImage = (product) => {
  // 如果商品有多张图片，返回第一张图片
  if (product.imagePath && product.imagePath.length > 0) {
    const imageFiles = product.imagePath.split(";");
    return imageFiles.length > 0 ? `${imageFiles[0]}` : ""; // 假设图片数组是 `images`
  }
  return "";
};

// 用于存储收藏夹商品信息
const collection = reactive({
  buyer_id: buyerId,
  product_id: "",
  products: [], // 用于存储收藏夹商品
});

// 获取用户收藏夹商品
const getUserCartItems = () => {
  request
    .get(`/collect/selectById/${buyerId}`)
    .then((res) => {
      if (res.data) {
        collection.products = res.data.map((product) => ({
          ...product,
          checked: false,
        }));
        console.log("收藏夹商品为：", collection.products);
      } else {
        collection.products = [];
        ElMessage({
          message: "收藏夹暂无商品",
          type: "warning",
        });
      }
    })
    .catch((error) => {
      console.error("获取收藏夹商品失败：", error);
      ElMessage({
        message: "获取收藏夹商品失败，请稍后重试",
        type: "error",
      });
    });
};

// 获取所有商品列表（展示给用户）
request
  .get("/product/selectAll")
  .then((res) => {
    data.productList = res.data;
  })
  .catch((error) => {
    console.error("获取商品列表失败：", error);
  });

// 分页查询
const load = () => {
  request
    .get("/product/selectPage", {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name,
      },
    })
    .then((res) => {
      data.tableData = res.data?.list;
      data.table = res.data?.total;
    });
};

// 页面加载时获取购物车数据
onMounted(() => {
  getUserCartItems();
  loadCategories();
});

// 进入商品详情页
const goToDetails = (id) => {
  try {
    request.get(`/product/selectById/${id}`).then((res) => {
      data.productsList = res.data;
      console.log("商品数据为：", res.data);
    });
    router.push({ name: "productDetails", params: { productId: id } });
  } catch (error) {
    console.error("获取商品详情数据出错：", error);
  }
};

// 删除收藏商品
const deleteCollect = (productId) => {
  request
    .delete("/collect/delCollectsBatch", {
      data: [productId],
    })
    .then(() => {
      ElMessage({
        message: "删除收藏成功",
        type: "success",
      });
      getUserCartItems(); // 刷新收藏列表
    })
    .catch((error) => {
      console.error("删除收藏失败：", error);
      ElMessage({
        message: "删除收藏失败，请稍后重试",
        type: "error",
      });
    });
};

// 全选状态
const checkAll = ref(false);
// 选中的商品ID数组
const selectedIds = ref([]);

// 处理全选状态改变
const handleCheckAllChange = (value) => {
  collection.products.forEach((product) => {
    product.checked = value;
  });
  if (value) {
    selectedIds.value = collection.products.map((product) => product.id);
  } else {
    selectedIds.value = [];
  }
};

// 处理单个商品选中状态改变
const handleCheckChange = (id) => {
  const isChecked = collection.products.find(
    (product) => product.id === id
  ).checked;
  if (isChecked) {
    selectedIds.value.push(id);
  } else {
    selectedIds.value = selectedIds.value.filter(
      (productId) => productId !== id
    );
  }
  checkAll.value = collection.products.every((product) => product.checked);
};

// 批量删除
const batchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage({
      message: "请选择要删除的商品",
      type: "warning",
    });
    return;
  }
  request
    .delete("/collect/delCollectsBatch", {
      data: selectedIds.value,
    })
    .then(() => {
      ElMessage({
        message: "批量删除收藏成功",
        type: "success",
      });
      getUserCartItems(); // 刷新收藏列表
      selectedIds.value = [];
      checkAll.value = false;
    })
    .catch((error) => {
      console.error("批量删除收藏失败：", error);
      ElMessage({
        message: "批量删除收藏失败，请稍后重试",
        type: "error",
      });
    });
};
</script>

<style scoped>
.select-all-container {
  margin-bottom: 20px;
}
</style>
